<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="card-box">
        <el-card>
          <div class="head-row">
            <div class="head">统计图表展示</div>
            <div class="tab">
              <div
                :class="current === 0 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 0;
                  getUserList();
                "
              >
                民警统计
              </div>
              <div
                :class="current === 1 ? 'tab-item active' : 'tab-item'"
                @click="
                  current = 1;
                  getComList();
                "
              >
                社区统计
              </div>
            </div>
          </div>
          <template v-if="current === 0">
            <el-row class="mt1">
              <el-form-item label="民警" prop="badgeNumber">
                <el-select
                  v-model="policeUserId"
                  filterable
                  placeholder="请输入民警姓名或警号搜索"
                  style="width: 240px"
                  @change="initUserComStat"
                >
                  <el-option
                    v-for="item in polices"
                    :key="item.policeUserId"
                    :label="`${item.userName}-${item.badgeNumber}`"
                    :value="item.policeUserId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="时间" class="ml4">
                <el-date-picker
                  v-model="userYears"
                  type="year"
                  placeholder="请选择"
                  format="YYYY年"
                  value-format="YYYY"
                  @change="getUserList"
                />
              </el-form-item>
              <el-form-item class="ml4">
                <el-button type="primary" icon="Search" @click="getUserList"
                  >查询</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
            <el-row class="mt1" :gutter="50">
              <el-col :span="12">
                <div ref="evayear" style="height: 300px" />
              </el-col>
              <el-col :span="12">
                <el-radio-group
                  v-model="effectiveStatus"
                  @change="initUserComStatSort()"
                >
                  <el-radio :value="10">全部</el-radio>
                  <el-radio :value="1">有效</el-radio>
                  <el-radio :value="0">无效</el-radio>
                </el-radio-group>
                <div ref="evanum" style="height: 300px" />
              </el-col>
            </el-row>
            <div
              class="mt2 el-table el-table--enable-row-hover el-table--medium"
            >
              <el-table v-loading="loading" :data="tableList1" border>
                <el-table-column label="时间" prop="months" align="center">
                  <template #default="scope">
                    {{
                      scope.row.months != "全部"
                        ? scope.row.months + "月"
                        : scope.row.months
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="投诉人数"
                  prop="complaintUserCount"
                  align="center"
                />
                <el-table-column
                  label="投诉次数"
                  prop="totalComplaintCount"
                  align="center"
                />
                <el-table-column
                  label="有效投诉次数"
                  prop="validComplaintCount"
                  align="center"
                />
                <el-table-column
                  label="无效投诉次数"
                  prop="invalidComplaintCount"
                  align="center"
                />
              </el-table>
            </div>
          </template>
          <template v-if="current === 1">
            <el-row class="mt1">
              <el-col :span="4" style="display: flex; justify-content: center">
                <el-radio-group
                  v-model="queryParams.type"
                  @change="changeQuery"
                >
                  <el-radio :value="1">按年</el-radio>
                  <el-radio :value="0">按月</el-radio>
                </el-radio-group>
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="queryParams.yearMonth"
                  :type="queryParams.type == 1 ? 'year' : 'month'"
                  placeholder="请选择"
                  :format="queryParams.type == 1 ? 'YYYY年' : 'YYYY年MM月'"
                  :value-format="queryParams.type == 1 ? 'YYYY' : 'YYYY-MM'"
                  @change="getComList"
                />
              </el-col>
            </el-row>
            <el-row class="mt1" :gutter="50">
              <el-col :span="12">
                <div
                  class="el-table el-table--enable-row-hover el-table--medium"
                >
                  <div ref="complainstatByType" style="height: 290px" />
                </div>
              </el-col>
              <el-col :span="12" v-if="queryParams.type == 1">
                <div
                  class="el-table el-table--enable-row-hover el-table--medium"
                  style="position: relative"
                >
                  <div class="flex-row community-query">
                    <div>社区：</div>
                    <el-select
                      v-model="queryParams.communityId"
                      :empty-values="[null]"
                      :value-on-clear="null"
                      placeholder="请选择社区"
                      size="large"
                      style="width: 160px"
                      clearable
                      @change="changeCommunity"
                    >
                      <el-option
                        v-for="dict in community_options"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                      />
                    </el-select>
                  </div>
                  <div ref="complainstat" style="height: 290px" />
                </div>
              </el-col>
            </el-row>
            <div class="mt1">
              <div class="flex flex-c items-center flex-end mb10">
                <el-button
                  type="primary"
                  plain
                  icon="Download"
                  @click="handleExport"
                  v-hasPermi="[
                    'crowdInfo:reportAndComplaint:complaintStatistics:export',
                  ]"
                  >导出报表</el-button
                >
              </div>
              <div class="el-table el-table--enable-row-hover el-table--medium">
                <el-table v-loading="loading" :data="tableList" border>
                  <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="70"
                  />
                  <el-table-column
                    :label="queryParams.type == 1 ? '年份' : '月份'"
                    prop="yearMonth"
                    align="center"
                  />
                  <el-table-column
                    label="社区名称"
                    prop="communityName"
                    align="center"
                  />
                  <el-table-column
                    :label="queryParams.type == 1 ? '年投诉人数' : '月投诉人数'"
                    prop="complaintUserCount"
                    align="center"
                  >
                    <template #default="scope">
                      <span style="color: #038afe">{{
                        scope.row.complaintUserCount
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="queryParams.type == 1 ? '年投诉次数' : '月投诉次数'"
                    prop="sumCount"
                    align="center"
                  />
                  <el-table-column
                    :label="
                      queryParams.type == 1
                        ? '年有效投诉次数'
                        : '月有效投诉次数'
                    "
                    prop="invalidCount"
                    align="center"
                  />
                  <el-table-column
                    :label="
                      queryParams.type == 1
                        ? '年无效投诉次数'
                        : '月无效投诉次数'
                    "
                    prop="effectiveCount"
                    align="center"
                  />
                  <el-table-column
                    :label="queryParams.type == 1 ? '同比' : '环比'"
                    prop="percentage"
                    align="center"
                  >
                    <template #default="scope">
                      <div style="display: flex; justify-content: center">
                        <div
                          style="
                            min-width: 25%;
                            display: flex;
                            justify-content: flex-start;
                            align-items: center;
                          "
                        >
                          <svg-icon
                            v-if="scope.row.percentage.includes('-')"
                            color="#33A954"
                            icon-class="descend"
                            class="el-input__icon input-icon"
                            style="width: 16px"
                          />
                          <svg-icon
                            v-else
                            color="#F55300"
                            icon-class="rise"
                            class="el-input__icon input-icon"
                            style="width: 16px"
                          />
                          <span v-if="scope.row.percentage.includes('-')">
                            {{ scope.row.percentage.substring(1) }}</span
                          >
                          <span v-else> {{ scope.row.percentage }}</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="ComplaintStatistics">
import {
  getComplaintStat,
  userComplaintStat,
  userComplaintStatSort,
} from "@/api/crowdInfo/complaint";
import { listPoliceBySearch } from "@/api/community/police";
import { getCommunity } from "@/api/community/community";
import {
  initComplainstatByTypeChart,
  initComplainstatChart,
  initUserEvaYearChart,
  initUserEvaNumSortChart,
} from "./chart";
import * as echarts from "echarts";
import dayjs from "dayjs";

const { proxy } = getCurrentInstance();
const current = ref(0);
const complainstatByType = ref(null);
const complainstat = ref(null);
const community_options = ref([]);
const evayear = ref(null);
const evanum = ref(null);
const tableList1 = ref([]); //个人
const tableList = ref([]); //社区
const policeUserId = ref(undefined);
const polices = ref([]);
const data = reactive({
  queryParams: {
    type: 0, //0月 1年，默认月
    yearMonth: dayjs(new Date()).format("YYYY-MM"),
    communityId: "",
  },
  userYears: dayjs(new Date()).format("YYYY"),
  effectiveStatus: 10,
});
const { queryParams, userYears, effectiveStatus } = toRefs(data);

function getComList(e) {
  if (queryParams.value.type == 0) {
    queryParams.value.communityId = "";
  } else {
    if (queryParams.value.communityId) {
      changeCommunity();
    }
  }
  let param = {
    type: queryParams.value.type,
    yearMonth: queryParams.value.yearMonth,
  };
  proxy.$modal.loading("正在加载举报投诉统计图表数据，请稍候！");
  getComplaintStat(param)
    .then((response) => {
      proxy.$modal.closeLoading();
      const { data } = response;

      // 投诉统计图-月/年
      const complainstatByTypeIntance = echarts.init(
        complainstatByType.value,
        "macarons"
      );
      data.cltCmyChartVos = data.cltCmyChartVos ?? [];
      let xdata = [];
      let ydata = [];
      if (data.cltCmyChartVos.length) {
        data.cltCmyChartVos.forEach((item) => {
          xdata.push(item.communityName);
          ydata.push(+item.communityCount);
        });
      }
      complainstatByTypeIntance.setOption(
        initComplainstatByTypeChart(
          xdata,
          ydata,
          +data.invalidCount,
          +data.effectiveCount,         
          +data.sumCount
        )
      );

      // 时间选择改变 社区统计柱状图也要同步改变
      if (e) {
        const complainstatInstance = echarts.init(
          complainstat.value,
          "macarons"
        );
        data.cltCmyMonthChartVos = data.cltCmyMonthChartVos ?? [];
        let xdata = [];
        let ydata = [];
        if (data.cltCmyMonthChartVos.length) {
          data.cltCmyMonthChartVos.forEach((item) => {
            xdata.push(item.month);
            ydata.push(+item.monthCount);
          });
        }
        complainstatInstance.setOption(initComplainstatChart(xdata, ydata));
      }

      // 表格
      tableList.value = data.cltTableVos ?? [];

      window.addEventListener("resize", () => {
        complainstatByTypeIntance.resize();
        complainstatInstance.resize();
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

/** 导出按钮操作 */
function handleExport() {
  let param = proxy.download(
    "complaint/exportCmtStatisticsExcel",
    {
      type: queryParams.value.type,
      yearMonth: queryParams.value.yearMonth,
    },
    `群众投诉统计报表_${new Date().getTime()}.xlsx`
  );
}

/** 查询社区下拉列表数据 */
function getCommunityList() {
  getCommunity({}).then((response) => {
    const { data } = response;
    community_options.value = data;
    community_options.value.unshift({
      id: "",
      name: "全部",
    });
  });
}

function changeQuery() {
  if (queryParams.value.type == 1) {
    queryParams.value.yearMonth = String(new Date().getFullYear());
    getCommunityList();
  } else {
    queryParams.value.communityId = "";
    queryParams.value.yearMonth = dayjs(new Date()).format("YYYY-MM");
  }
  getComList();
  if (queryParams.value.type == 1) changeCommunity();
}

function changeCommunity() {
  getComplaintStat(queryParams.value).then((response) => {
    const { data } = response;

    // 投诉统计图
    if (queryParams.value.type == 1) {
      const complainstatInstance = echarts.init(complainstat.value, "macarons");
      data.cltCmyMonthChartVos = data.cltCmyMonthChartVos ?? [];
      let xdata = [];
      let ydata = [];
      if (data.cltCmyMonthChartVos.length) {
        data.cltCmyMonthChartVos.forEach((item) => {
          xdata.push(item.month);
          ydata.push(+item.monthCount);
        });
      }
      complainstatInstance.setOption(initComplainstatChart(xdata, ydata));
    }

    window.addEventListener("resize", () => {
      complainstatInstance.resize();
    });
  });
}

function resetQuery() {
  tableList1.value = [];
  policeUserId.value = undefined;
  userYears.value = dayjs(new Date()).format("YYYY");
  const evayearInstance = echarts.init(evayear.value, "macarons");
  evayearInstance.setOption(initUserEvaYearChart());
  window.addEventListener("resize", () => {
    evayearInstance.resize();
  });
  initUserComStatSort();
}

function getUserList() {
  initUserComStat();
  initUserComStatSort();
}

function initUserComStat() {
  proxy.$modal.loading("正在加载举报投诉统计图表数据，请稍候！");
  userComplaintStat({
    ...{ policeUserId: policeUserId.value },
    ...{ years: userYears.value },
  })
    .then((response) => {
      proxy.$modal.closeLoading();
      const { data } = response;
      nextTick(() => {
        // 评价总数
        const evayearInstance = echarts.init(evayear.value, "macarons");
        let xdata = [];
        let ydata = [];
        let chartData = data.yearVos ?? [];
        if (chartData.length) {
          chartData.forEach((item) => {
            xdata.push(item.month + "月");
            ydata.push(item.monthCount);
          });
        }
        evayearInstance.setOption(
          initUserEvaYearChart(
            xdata,
            ydata,
            `${data.userName ?? ""}-${data.badgeNumber ?? ""}`
          )
        );
        // 初始化表格数据
        tableList1.value = data.complaintStatsVos ?? [];
        window.addEventListener("resize", () => {
          evayearInstance.resize();
        });
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

// 纵向柱状图
function initUserComStatSort() {
  userComplaintStatSort({
    ...{ effectiveStatus: effectiveStatus.value },
    ...{ years: userYears.value },
  })
    .then((response) => {
      const { data } = response;
      let list = data ?? [];
      let xdata = [];
      let ydata = [];
      let comArr = [];
      if (list.length) {
        list.forEach((item) => {
          xdata.push(item.userName);
          ydata.push(item.communityCount);
          comArr.push(item.communityName);
        });
      }
      const evanumInstance = echarts.init(evanum.value, "macarons");
      evanumInstance.setOption(
        initUserEvaNumSortChart(xdata, ydata, comArr),
        true
      );

      window.addEventListener("resize", () => {
        evanumInstance.resize();
      });
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
    });
}

// 民警列表
function listPolice() {
  listPoliceBySearch({ key: "" })
    .then((response) => {
      const { data } = response;
      polices.value = data;
    })
    .catch((err) => {});
}

onMounted(() => {
  listPolice();
  if (policeUserId.value) {
    getUserList();
  } else {
    const evayearInstance = echarts.init(evayear.value, "macarons");
    evayearInstance.setOption(initUserEvaYearChart());
    window.addEventListener("resize", () => {
      evayearInstance.resize();
    });
    initUserComStatSort();
  }
});
</script>
<style lang="scss" scoped>
.head {
  font-weight: bold;
  font-size: 1.5em;
  color: #000;
  margin-bottom: 15px;
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 1rem;
  color: #000;
  .label {
    margin-left: 20px;
  }
}
.community-query {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  :deep(.el-select__wrapper) {
    min-height: 32px;
  }
}
</style>
